package com.inspinia.base.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;


/**
 * 简单的邮件发送
 * 
 * @author Administrator
 * 
 */
public class EmailUtils {

//	public static void main(String[] args) throws Exception {
//		Properties prop = new Properties();
//		InputStream in = SpringTaskController.class.getResourceAsStream("/service.properties");
//		prop.load(in);
//		EmailUtils.sendMail(prop.getProperty("fromEmail"), prop.getProperty("toEmail"), prop.getProperty("emailName"), prop.getProperty("emailPassword"), "１１１１１１１１", "１１１１１１１");
//	}
	/**
	 * 发送邮件　(暂时只支持163邮箱发送)
	 * @param title　发送主题
	 * @param centent　发送内容
	 * @throws Exception
	 */
	public static void sendMail(String title,String centent){
		try {
			Properties prop = PropertiesUtils.getProperties("/email.properties");
			Properties properties = new Properties();// 创建Properties对象
			properties.put("mail.transport.protocol", prop.getProperty("transportProtocol"));// 设置传输协议
			properties.put("mail.smtp.host",  prop.getProperty("mailAddress"));// 设置发信邮箱的smtp地址
			properties.put("mail.smtp.auth", prop.getProperty("smtpAuth")); // 验证
			// 发件人的账号
			properties.put("mail.user", prop.getProperty("emailName"));
			// 访问SMTP服务时需要提供的密码
			properties.put("mail.password", prop.getProperty("emailPassword"));
			Authenticator auth = new AjavaAuthenticator(properties.getProperty("mail.user"),
					properties.getProperty("mail.password")); // 使用验证，创建一个Authenticator
			Session session = Session.getDefaultInstance(properties, auth);// 根据Properties，Authenticator创建Session
			Message message = new MimeMessage(session);// Message存储发送的电子邮件信息
			// 设置发件人
			InternetAddress form = new InternetAddress(String.valueOf(prop.get("fromEmail")));
			message.setFrom(form);
			// 设置收件人
			InternetAddress to = new InternetAddress(String.valueOf(prop.get("toEmail")));
			message.setRecipient(Message.RecipientType.TO, to);
			// 指定邮箱内容及ContentType和编码方式
			message.setContent(centent, "text/html;charset=utf-8");
			message.setSubject(title);// 设置主题
			message.setSentDate(new Date());// 设置发信时间
			Transport.send(message);// 发送
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

// 创建传入身份验证信息的 Authenticator类
class AjavaAuthenticator extends Authenticator {
	private String user;
	private String pwd;

	public AjavaAuthenticator(String user, String pwd) {
		this.user = user;
		this.pwd = pwd;
	}

	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(user, pwd);
	}
}